/**
 * Description
 *
 * Creation Date 18/10/2017
 * @author Candy
 */

import {
  INIT_BUYCART,
  CLEAR_CART,
  ADD_CART,
  REDUCE_CART,
  BUY_CART,
  GET_USERINFO,
  RECORD_USERINFO,
  OUT_LOGIN
} from './mutation-types'

import {setStore, getStore, removeStore} from '../config/mUtils'

export default  {
  //初始化购物城
  [INIT_BUYCART](state) {
    let initCart = getStore('buyCart');
    if(initCart) {
      state.cartList = JSON.parse(initCart)
    }
  },
  //加入购物车
  [ADD_CART](state, {product_id, name, price, image}) {
    let cart = state.cartList;
    if(cart[product_id]) {
      cart[product_id]['num']++
    } else {
      cart[product_id] = {
        num: 1,
        id: product_id,
        name,
        price,
        image,
      }
    }
    state.cartList = {...cart};
    setStore('buyCart', JSON.stringify(state.cartList))
  },
  //清空购物车
  [CLEAR_CART](state) {
    state.cartList ={}
    removeStore('buyCart')
  },
  //移除购物车
  [REDUCE_CART](state, product_id) {
    let cartInfo = state.cartList;
    if(cartInfo && cartInfo[product_id]) {
      if(cartInfo[product_id]['num'] > 1) {
        cartInfo[product_id]['num']--;
        state.cartList = {...cartInfo}
      } else {
        cartInfo[product_id] = null
        let cartObj = {}
        Object.values(cartInfo).forEach(item => {
          if(item != null) {
            return cartObj[item.id] = item
          }
        })
        state.cartList = {...cartObj}
      }
      setStore('buyCart', state.cartList);
    }
  },
  [RECORD_USERINFO](state, info) {
    state.userInfo = info;
    state.login = true;
    setStore('user_id', info.user_id)
  },
  [GET_USERINFO](state, info) {
    // if(state.userInfo && state.userInfo.username !== info.username) {
    //   return
    // }
    if (!state.login) {
      return
    }
    if(!info.message) {
      state.userInfo = {...info}
    } else {
      state.userInfo = null
    }
  },
  [OUT_LOGIN](state) {
    state.userInfo = {};
    state.login = false;
    removeStore('user_id')
  },
}
